package com.ruoyi.androidPad.mqtt.config;

import com.alibaba.fastjson.JSON;
import com.ruoyi.androidPad.domain.SetInformation;
import com.ruoyi.xag.domain.iotdevice.IotDevice;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


/**
 * @Classname PushCallback
 * @Description 消费监听类
 *
 * @author Mr-Le
 */
@Component
public class PushCallback implements MqttCallback {
    private static final Logger logger = LoggerFactory.getLogger(MqttPushClient.class);

    private static final String PAD_DEVICE_INFO_TOPIC = "android/pad/info";

    @Autowired
    private MqttConfig mqttConfig;

    @Autowired
    private MqttPushClient mqttPushClient;

    private static MqttClient client;

    @Override
    public void connectionLost(Throwable throwable) {
        // 连接丢失后，一般在这里面进行重连
        logger.info("连接断开，可以做重连");
        if (client == null || !client.isConnected()) {
            mqttConfig.getMqttPushClient();
        }
    }

    /**
     * 消息发送到服务器传递，同时订阅的主题也再此处理
     * @param topic 主题
     * @param mqttMessage  消息
     * @throws Exception
     */
    @Override
    public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception {
        // subscribe后得到的消息会执行到这里面
        logger.info("接收消息主题 : " + topic);
        logger.info("接收消息Qos : " + mqttMessage.getQos());
        logger.info("接收消息内容 : " + new String(mqttMessage.getPayload()));


        switch (topic){
            case PAD_DEVICE_INFO_TOPIC:
                SetInformation setInformation = JSON.parseObject(new String(mqttMessage.getPayload()), SetInformation.class);
                System.out.println(setInformation.toString());
                break;
            case "保留":
                System.out.println("保留字段" + new String(mqttMessage.getPayload()));
                break;
            default:
                break;
        }
    }

    /**
     * 消息发送到客户端可使用
     * @param iMqttDeliveryToken 消息token
     */
    @Override
    public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
        logger.info("deliveryComplete---------" + iMqttDeliveryToken.isComplete());
    }

    public void judgeTopicAction(String topic) {

    }
}
